#ifndef FRAMELESSWINDOW_H
#define FRAMELESSWINDOW_H

#include <QApplication>
#include <QMainWindow>
#include <QMouseEvent>
#include <QPoint>
#include <QScreen>
#include <QTimer>
#include <QWidget>

#ifdef Q_OS_WIN
#include <dwmapi.h>
#include <windows.h>
#endif

// 检查是否已经定义了 MARGINS 结构体
#ifndef _MARGINS_DEFINED
#define _MARGINS_DEFINED

// 手动定义 MinGW 可能缺少的常量和结构
#ifndef GET_X_LPARAM
#define GET_X_LPARAM(lp) ((int)(short)LOWORD(lp))
#define GET_Y_LPARAM(lp) ((int)(short)HIWORD(lp))
#endif

#ifndef DWMWA_USE_HOSTBACKDROPBRUSH
#define DWMWA_USE_HOSTBACKDROPBRUSH 34
#endif

#ifndef DWMWA_NCRENDERING_POLICY
#define DWMWA_NCRENDERING_POLICY 2
#define DWMNCRP_ENABLED 2
#endif

// Windows 11 圆角设置
#ifndef DWMWA_WINDOW_CORNER_PREFERENCE
#define DWMWA_WINDOW_CORNER_PREFERENCE 33
#define DWMWCP_DEFAULT 0
#define DWMWCP_DONOTROUND 1
#define DWMWCP_ROUND 2
#define DWMWCP_ROUNDSMALL 3
#endif

// 使用不同的名称定义结构体以避免冲突
typedef struct tagMyMargins {
    int cxLeftWidth;
    int cxRightWidth;
    int cyTopHeight;
    int cyBottomHeight;
} MyMargins, *PMyMargins;

#endif // _MARGINS_DEFINED

class FramelessWindow : public QMainWindow {
    Q_OBJECT

  public:
    explicit FramelessWindow(QWidget *parent = nullptr);
    void setTitleBar(QWidget *titleBar); // 设置可拖动的标题栏控件
    QScreen *currentScreen() const;      // 获取当前屏幕
    void showMaximized();                // 重写最大化/最小化方法
    void showNormal();
    void showMinimized();
    bool isMaximized() const;

  signals:
    void windowStateChanged(); // 添加信号声明

  protected:
    bool nativeEvent(const QByteArray &eventType, void *message, long *result) override;
    void mousePressEvent(QMouseEvent *event) override;
    void mouseMoveEvent(QMouseEvent *event) override;
    void mouseReleaseEvent(QMouseEvent *event) override;
    // void mouseDoubleClickEvent(QMouseEvent *event) override;
    bool eventFilter(QObject *obj, QEvent *event) override;
    void changeEvent(QEvent *event) override;
    void paintEvent(QPaintEvent *event) override;
    bool event(QEvent *event) override;


  private:
    bool isDragging = false;
    QPoint dragPosition;
    QWidget *titleBar = nullptr;  // 标题栏控件
    bool m_isMaximized = false;   // 窗口状态
    QRect m_normalGeometry;       // 保存正常状态下的几何信息
    const int m_nBorderWidth = 6; // 窗口边框宽度
    bool m_isMinimized = false;       // 新增：标记是否处于最小化状态
    bool m_wasMaximizedBeforeMinimize = false; // 新增：记录最小化前是否为最大化

    bool handleWinEvent(void *message, long *result); // 处理Windows消息
    void updateCursor(int hitTestResult);             // 更新鼠标样式
    void updateWindowMargins();                       // 更新窗口边框
    void updateWindowCornerPreference();              // 启用Windows 11圆角
    
};

#endif // FRAMELESSWINDOW_H